const express = require('express');
const router = express.Router();
const Appointment = require('../models/Appointment');
const { query, formatRows } = require('../config/database');
const { authenticateToken, optionalAuth } = require('../middleware/auth');
const {
  validateAppointmentCreation,
  validateAppointmentUpdate,
  validateId,
  validatePagination,
  validateSearch
} = require('../middleware/validation');

// 获取预约列表
router.get('/', optionalAuth, validatePagination, validateSearch, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const { keyword, category_id, status } = req.query;
    
    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const params = [];

    if (keyword) {
      whereClause += ' AND (a.title LIKE ? OR a.game_name LIKE ? OR a.description LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`, `%${keyword}%`);
    }

    if (category_id) {
      // 如果是数字，按ID搜索；如果是字符串，按名称搜索
      if (/^\d+$/.test(category_id)) {
        whereClause += ' AND a.category_id = ?';
        params.push(category_id);
      } else {
        whereClause += ' AND gc.name = ?';
        params.push(category_id);
      }
    }

    if (status) {
      whereClause += ' AND a.status = ?';
      params.push(status);
    } else {
      // 默认只显示活跃的预约
      whereClause += ' AND a.status = ?';
      params.push('active');
    }

    // 只显示公开的预约（除非是创建者）
    if (!req.user) {
      whereClause += ' AND a.is_public = ?';
      params.push(true);
    }

    // 获取总数
    const countSql = `
      SELECT COUNT(*) as total
      FROM appointments a
      LEFT JOIN users u ON a.creator_id = u.id
      LEFT JOIN game_categories gc ON a.category_id = gc.id
      ${whereClause}
    `;

    const countResult = await query(countSql, params);
    const total = countResult[0].total;

    // 获取列表数据
    const offset = (page - 1) * limit;
    const listSql = `
      SELECT
        a.*,
        u.username as creator_username,
        u.nickname as creator_nickname,
        gc.name as category_name,
        gc.icon as category_icon
      FROM appointments a
      LEFT JOIN users u ON a.creator_id = u.id
      LEFT JOIN game_categories gc ON a.category_id = gc.id
      ${whereClause}
      ORDER BY a.created_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `;

    const rows = await query(listSql, params);
    const appointments = formatRows(rows);

    // 为每个预约获取参与者数量和简化的参与者列表
    for (const appointment of appointments) {
      const participantSql = `
        SELECT COUNT(*) as count
        FROM appointment_participants
        WHERE appointment_id = ?
      `;
      const participantCount = await query(participantSql, [appointment.id]);
      appointment.current_players = participantCount[0].count;

      // 获取简化的参与者列表（只包含用户名）
      const participantListSql = `
        SELECT u.username
        FROM appointment_participants ap
        JOIN users u ON ap.user_id = u.id
        WHERE ap.appointment_id = ?
        ORDER BY ap.joined_at ASC
      `;
      const participants = await query(participantListSql, [appointment.id]);
      appointment.participants = participants.map(p => p.username);
    }

    const result = {
      data: appointments,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    };
    
    res.json({
      success: true,
      data: result.data,
      pagination: result.pagination
    });
  } catch (error) {
    console.error('获取预约列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取预约列表失败'
    });
  }
});

// 获取单个预约详情
router.get('/:id', validateId, optionalAuth, async (req, res) => {
  try {
    const appointmentId = req.params.id;
    const appointment = await Appointment.findById(appointmentId);
    
    if (!appointment) {
      return res.status(404).json({
        success: false,
        message: '预约不存在'
      });
    }
    
    // 检查是否有权限查看私有预约
    if (!appointment.is_public && 
        (!req.user || req.user.id !== appointment.creator_id)) {
      return res.status(403).json({
        success: false,
        message: '无权限查看此预约'
      });
    }
    
    res.json({
      success: true,
      data: appointment
    });
  } catch (error) {
    console.error('获取预约详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取预约详情失败'
    });
  }
});

// 创建预约
router.post('/', authenticateToken, validateAppointmentCreation, async (req, res) => {
  try {
    const appointmentData = {
      ...req.body,
      creator_id: req.user.id
    };

    const appointmentId = await Appointment.create(appointmentData);
    const appointment = await Appointment.findById(appointmentId);

    res.status(201).json({
      success: true,
      message: '预约创建成功',
      data: appointment
    });
  } catch (error) {
    console.error('创建预约错误:', error);
    res.status(500).json({
      success: false,
      message: '创建预约失败'
    });
  }
});

// 更新预约
router.put('/:id', authenticateToken, validateId, validateAppointmentUpdate, async (req, res) => {
  try {
    const appointmentId = req.params.id;
    
    const updatedAppointment = await Appointment.update(
      appointmentId, 
      req.body, 
      req.user.id
    );
    
    res.json({
      success: true,
      message: '预约更新成功',
      data: updatedAppointment
    });
  } catch (error) {
    console.error('更新预约错误:', error);
    
    if (error.message === '预约不存在' || error.message === '只有创建者可以修改预约') {
      return res.status(403).json({
        success: false,
        message: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '更新预约失败'
    });
  }
});

// 删除预约
router.delete('/:id', authenticateToken, validateId, async (req, res) => {
  try {
    const appointmentId = req.params.id;
    
    await Appointment.delete(appointmentId, req.user.id);
    
    res.json({
      success: true,
      message: '预约删除成功'
    });
  } catch (error) {
    console.error('删除预约错误:', error);
    
    if (error.message === '预约不存在' || error.message === '只有创建者可以删除预约') {
      return res.status(403).json({
        success: false,
        message: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '删除预约失败'
    });
  }
});

// 获取我的预约列表
router.get('/my/list', authenticateToken, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    
    const conditions = {
      'a.creator_id': req.user.id
    };
    
    const result = await Appointment.getList(conditions, page, limit);
    
    res.json({
      success: true,
      data: result.data,
      pagination: result.pagination
    });
  } catch (error) {
    console.error('获取我的预约列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取我的预约列表失败'
    });
  }
});

// 获取我参与的预约列表
router.get('/my/participated', authenticateToken, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    
    // 这里需要特殊的查询，因为需要通过参与者表来查询
    const conditions = {
      'ap.user_id': req.user.id
    };
    
    // 修改查询以包含参与者表的连接
    const result = await Appointment.getList(conditions, page, limit);
    
    res.json({
      success: true,
      data: result.data,
      pagination: result.pagination
    });
  } catch (error) {
    console.error('获取参与的预约列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取参与的预约列表失败'
    });
  }
});

// 退出预约
router.delete('/:id/participants/me', authenticateToken, validateId, async (req, res) => {
  try {
    const appointmentId = req.params.id;
    
    await Appointment.removeParticipant(appointmentId, req.user.id);
    
    res.json({
      success: true,
      message: '已退出预约'
    });
  } catch (error) {
    console.error('退出预约错误:', error);
    
    if (error.message === '用户未参与此预约') {
      return res.status(400).json({
        success: false,
        message: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '退出预约失败'
    });
  }
});

module.exports = router;
